# coding=utf-8
import _thread
import time
from tkinter import scrolledtext, Tk, BOTH, LEFT, END

from service.alipay import Alipay


class DashBoard:
    def __init__(self):
        self.window = Tk()
        self.window.title("华星支付-日志")
        self.window.iconbitmap('favicon.ico')
        # 窗口大小
        width, height = 600, 500
        # 窗口居中显示
        self.window.geometry('%dx%d+%d+%d' % (
            width, height, (self.window.winfo_screenwidth() - width) / 2,
            (self.window.winfo_screenheight() - height) / 2))
        self.window.maxsize(width, height)
        self.window.minsize(width, height)

        self.text = scrolledtext.ScrolledText(self.window, bg='white', width=50, height=20)
        self.text.place(x=50, y=50)
        self.text.pack(fill=BOTH, side=LEFT, expand=True)
        self.text.focus_set()
        self.text_line_count = 0
        self.text.insert(END, "##################################\n")
        self.text.insert(END, "#        请不要关闭本窗口        #\n")
        self.text.insert(END, "##################################\n")
        _thread.start_new_thread(self.alipay, ())
        self.window.mainloop()

    def alipay(self):
        time.sleep(1)
        Alipay().init(self).run()

    def logln(self):
        self.__log()

    def log_simple(self, log):
        self.__log(log=log)

    def log(self, log):
        self.__log('#> ', log, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    def __log(self, start=None, log=None, current_time=None):
        if self.text_line_count == 500:
            self.text.delete('1.0', END)
            self.text_line_count = 0
        self.text_line_count += 1
        if start and log and current_time:
            self.text.insert(END, start + log + '    ' + current_time + '\n')
        elif not start and log and not current_time:
            self.text.insert(END, log + '\n')
        else:
            self.text.insert(END, '\n')

        self.text.see(END)
